package com.ldz.elastic.task;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.ldz.elastic.model.Test;
import com.ldz.elastic.service.TestService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * Job类需要实现SimpleJob接口
 * @Author: ldz
 * @Date: 2018-05-04 15:29
 */
@Component
public class MyTestSimpleJob implements SimpleJob {
    @Autowired
    private TestService testService;
    /**
     * 实现execute方法，业务逻辑相关的代码在此方法编写
     * @param shardingContext  分片相关信息
     */
    @Override
    public void execute(ShardingContext shardingContext) {
        System.out.println("JobName:" + shardingContext.getJobName() + ", ShardingItem:" + shardingContext.getShardingItem() + ", " +
                "ShardingParameter:" + shardingContext.getShardingParameter() + ", " + "ShardingTotalCount:" + shardingContext.getShardingTotalCount() +
                ", " + "TaskId:" + shardingContext.getTaskId());

        /**
         *业务逻辑的执行
         * 这里根据 ShardingTotalCount 和 ShardingItem 来获取当前分片需要处理的数据
         */
        List<Test> list = testService.list(shardingContext.getShardingTotalCount(), shardingContext.getShardingItem());
        for (Test test : list) {
            testService.update(test.getId(), System.getProperty("server.port"));
            System.out.println(DateFormatUtils.format(new Date(), "yyyy-mm-dd HH:mm:ss:SSS") + " update id : " + test.getId());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
